//
//  NewChangeNicknameAlertView.m
//  ocCrazy
//
//  Created by Ajen on 2019/4/2.
//  Copyright © 2019 dukai. All rights reserved.
//

#import "NewChangeNicknameAlertView.h"

@implementation NewChangeNicknameAlertView{
    UIView * inputBg;
    UITextField * inputView;
    UILabel * hintLabel;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
        [tap addTarget:self action:@selector(removeFromSuperview)];
        [self addGestureRecognizer:tap];
        
        inputBg = [UIView new];
        inputBg.backgroundColor = [UIColor whiteColor];
        [self addSubview:inputBg];
        [inputBg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self);
            make.height.equalTo(@(163 - 50));
        }];
        
        inputView = [UITextField new];
        inputView.aj_bgColorHexStr(@"#f2f2f2").aj_addToView(inputBg);
        inputView.textAlignment = 1;
        inputView.delegate = self;
        inputView.clearButtonMode = UITextFieldViewModeWhileEditing;
        inputView.returnKeyType = UIReturnKeyContinue;
        [inputView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.equalTo(inputBg).offset(20);
            make.right.equalTo(inputBg).offset(-20);
            make.height.equalTo(@(86 - 50));
        }];
        [inputView becomeFirstResponder];
        
        
        hintLabel = [UILabel new];
        hintLabel.aj_Text(@"请输入要增加的栏目名(15字以内)").aj_font([UIFont systemFontOfSize:13 weight:UIFontWeightRegular]).aj_textColorHexStr(@"#cbcbcb").aj_addToView(inputBg);
        [hintLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(inputBg).offset(20);
            make.top.equalTo(inputView.mas_bottom).offset(19);
        }];
        
        UIButton * commitButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        commitButton.aj_buttonFont([UIFont systemFontOfSize:13 weight:UIFontWeightRegular]).aj_buttonTitle(@"确定").aj_buttonTintColorHex(@"#ffffff").aj_addTargetSelector(self,@selector(commitButtonDown)).aj_bgColor([UIColor colorWithAjenHex:0xf9c116 alpha:0.8]).aj_cornerRadius(4).aj_addToView(inputBg);
        [commitButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(@(55));
            make.height.equalTo(@(25));
            make.right.equalTo(inputBg).offset(-(20));
            make.centerY.equalTo(hintLabel);
        }];
        
        // 添加通知监听见键盘弹出/退出
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardAction:) name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardAction:) name:UIKeyboardWillHideNotification object:nil];
        
        [self layoutIfNeeded];
        
        //隐藏键盘上方toolbar
        if ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0 ) {
            inputView.inputAccessoryView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
        }
    }
    return self;
}

- (void)setAlertStr:(NSString *)alertStr {
    _alertStr = alertStr;
    hintLabel.aj_Text(alertStr);
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    return [self commitButtonDown];
}

-(BOOL)commitButtonDown{
    if([[LocalModel shared].titlesArray containsObject:inputView.text]){
        hintLabel.text = @"已有该栏目,请更换其他名字";
        hintLabel.textColor = [UIColor redColor];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [UIView animateWithDuration:0.2 animations:^{
                hintLabel.aj_textColorHexStr(@"#cbcbcb");
            }];
        });
        //获取到当前View的layer
        CALayer *viewLayer = hintLabel.layer;
        //获取当前View的位置
        CGPoint position = viewLayer.position;
        //移动的两个终点位置
        CGPoint beginPosition = CGPointMake(position.x + 10, position.y);
        CGPoint endPosition = CGPointMake(position.x - 10, position.y);
        //设置动画
        CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
        //设置运动形式
        [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];
        //设置开始位置
        [animation setFromValue:[NSValue valueWithCGPoint:beginPosition]];
        //设置结束位置
        [animation setToValue:[NSValue valueWithCGPoint:endPosition]];
        //设置自动反转
        [animation setAutoreverses:YES];
        //设置时间
        [animation setDuration:.06];
        //设置次数
        [animation setRepeatCount:3];
        //添加上动画
        [viewLayer addAnimation:animation forKey:nil];
        
        return NO;
    }else if(inputView.text.length > (self.maxLength ? self.maxLength : 15) || inputView.text.length == 0){
        hintLabel.aj_Text(_alertStr);
        hintLabel.textColor = [UIColor redColor];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [UIView animateWithDuration:0.2 animations:^{
                hintLabel.aj_textColorHexStr(@"#cbcbcb");
            }];
        });
        //获取到当前View的layer
        CALayer *viewLayer = hintLabel.layer;
        //获取当前View的位置
        CGPoint position = viewLayer.position;
        //移动的两个终点位置
        CGPoint beginPosition = CGPointMake(position.x + 10, position.y);
        CGPoint endPosition = CGPointMake(position.x - 10, position.y);
        //设置动画
        CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
        //设置运动形式
        [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];
        //设置开始位置
        [animation setFromValue:[NSValue valueWithCGPoint:beginPosition]];
        //设置结束位置
        [animation setToValue:[NSValue valueWithCGPoint:endPosition]];
        //设置自动反转
        [animation setAutoreverses:YES];
        //设置时间
        [animation setDuration:.06];
        //设置次数
        [animation setRepeatCount:3];
        //添加上动画
        [viewLayer addAnimation:animation forKey:nil];
        return NO;
    }else{
        if(self.commitBlock){
            self.commitBlock(inputView.text);
        }
        [inputView resignFirstResponder];
        return YES;
    }
}




// 键盘监听事件
- (void)keyboardAction:(NSNotification*)sender{
    NSDictionary *useInfo = [sender userInfo];
    NSValue *value = [useInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    if([sender.name isEqualToString:UIKeyboardWillShowNotification]){
        inputBg.alpha = 1;
        [inputBg mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self).offset(-1 * [value CGRectValue].size.height );
        }];
        [UIView animateWithDuration:0.3 animations:^{
            [self layoutIfNeeded];
        }];
    }else{
        [inputBg mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self);
        }];
        [UIView animateWithDuration:0.3 animations:^{
            [self layoutIfNeeded];
            inputBg.alpha = 0;
            self.backgroundColor = [UIColor colorWithAjenHex:0x000000 alpha:0];
        } completion:^(BOOL finished) {
            [super removeFromSuperview];
        }];
    }
}

-(void)removeFromSuperview{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [inputView resignFirstResponder];
    [inputBg mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self);
    }];
    [UIView animateWithDuration:0.3 animations:^{
        [self layoutIfNeeded];
        inputBg.alpha = 0;
        self.backgroundColor = [UIColor colorWithAjenHex:0x000000 alpha:0];
    } completion:^(BOOL finished) {
        [super removeFromSuperview];
    }];
}


-(void)setNormalNickName:(NSString *)normalNickName{
    _normalNickName = normalNickName;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        inputView.text = _normalNickName;
    });
    
}
@end
